<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/1/15
 * Time: 23:05
 */
namespace app\admin\logic\transfer_driver;
use app\common\library\BankMatch;
use app\common\library\Pingpp;
use think\exception\ValidateException;


/**
 * 打款上层服务
 */
class Tl extends Base
{
    private static $new; //申请一个私有的静态成员变量来保存该类的唯一实例

    public static function instance () { //声明一个静态公共方法，供外部获取唯一实例
        if (!(self::$new instanceof self)) {
            self::$new = new self;
        }
        return self::$new;
    }

    public function getTlCode($bank_cand) {
        $code = BankMatch::instance()->getCode($bank_cand);
        $bank_code = config('transfer_config.bank_name');
        if (isset($bank_code[$code])) {
            return $bank_code[$code][0];
        } else {
            throw new ValidateException('未获取到银行编码');
        }
    }
    public function pay($id) {
        $money = $this->getMoney($id);
        $user = $this->getUser($money['user_id']);
        try {
            $open_bank_code = $this->getTlCode($money['bank_card']);
            $data['order_sn'] = $money['order_sn'];
            $data['get_money'] = $money['get_money'];
            $data['id'] = $money['id'];
            $data['bank_card'] = $money['bank_card'];
            $data['real_name'] = $user['real_name'];
            $data['open_bank_code'] = $open_bank_code;

            Pingpp::getInstance()->transfer($data);
        } catch (\Exception $e) {
            $this->lineNotify($id, false);
            $this->log($money, 2, $e->getMessage(), '通联打款');
        }

        return true;
    }

    /*回调*/
    public function notify($event) {
        $id = $event['metadata']['order_id'];
        $money = $this->getMoney($id);

        if ($event['last_res'] == 1) {
            $this->lineNotify($id, true);
            $this->log($money, 1, '打款成功', '通联打款');
        } else {
            $this->lineNotify($id, false);
            $this->log($money, 2, '打款失败', '通联打款');
        }
    }

}